package net.app.zoneland.oauth.custom;

import net.app.zoneland.system.entity.SysUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description Jwt token扩展
 * @Author cjb
 * @CreateTime 2020/12/19 16:54
 * @Version: 1.0
 */
@Component
public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Object principal = authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();
        if(principal instanceof SysUser){
            SysUser user = (SysUser) authentication.getPrincipal();
            String username = user.getUsername();
            additionalInfo.put("username", username);
        }else{
            additionalInfo.put("client_id", principal);
        }
        // 注意添加的额外信息，最好不要和已有的json对象中的key重名，容易出现错误
        //additionalInfo.put("authorities", user.getAuthorities());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
